//
//  LeverOrderCell.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/5/8.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit
let nameTag = 1000
let inforTag = 2000
protocol LeverOrderCellDelegate:EntrustCellDelegate {
    
    /// 平仓
    ///
    /// - Parameter model: model
    func changePositionState(_ model:CoinOrderModel)
}
class LeverOrderCell: BaseTableViewCell {
    var model:CoinOrderModel = CoinOrderModel()
    var type:OrderSelectType?
    weak var delegate:LeverOrderCellDelegate?
    lazy var buyLabel: UILabel = {
        let label = UILabel()
        label.textColor = kThemeColor
        label.font = UIFont(name: "PingFang-SC-Heavy", size: 15)
        return label
    }()
    
    lazy var eventLabel: BaseLabel = {
        let label = BaseLabel(style: .oneStyle)
        label.font = UIFont(name: "PingFang-SC-Heavy", size: 16)
        return label
    }()
    
    lazy var scheduleLabel: BaseLabel = {
        let label = BaseLabel(style: .oneStyle)
//        label.text = "1/3"
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()
    //浮动盈亏价格
    lazy var scalePriceLabel:UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 15)
        return label
    }()
    
    lazy var positionBtn: UIButton =  {
        let btn = UIButton()
        btn.addTarget(self, action: #selector(positionBtnAction), for: UIControlEvents.touchUpInside)
        btn.setTitleColor(kThemeColor, for: UIControlState.normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        btn.layer.cornerRadius = 3
        btn.layer.borderColor = kThemeColor.cgColor
        btn.layer.borderWidth = 0.5
        return btn
    }()
    
    lazy var timeLabel: UILabel = {
        let label = BaseLabel(style: .thirdStyle)
//        label.text = "15:56-04/08"
        label.font = UIFont.systemFont(ofSize: 10)
        return label
    }()
    
    lazy var stateBtn: CustomBtn = {
        let btn = CustomBtn(style: .styleLeft)
        btn.nameLabel.font = UIFont.systemFont(ofSize: 14)
        return btn
    }()
    
    var entrustLabel:UILabel?
    var zsLabel:UILabel?
    var dqLabel:UILabel?
    var zyLabel:UILabel?
    var syLabel:UILabel?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    
    override func setUpUI() {
        super.setUpUI()
        self.contentView.addSubview(buyLabel)
        buyLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(20)
        }
        
        self.contentView.addSubview(eventLabel)
        eventLabel.snp.makeConstraints { (make) in
            make.left.equalTo(buyLabel.snp.right).offset(10)
            make.centerY.equalTo(buyLabel)
        }
        
        self.contentView.addSubview(scheduleLabel)
        scheduleLabel.snp.makeConstraints { (make) in
            make.left.equalTo(eventLabel.snp.right).offset(20)
            make.centerY.equalTo(buyLabel)
            make.width.lessThanOrEqualTo(kSCREEN_WIDTH/2)
        }
        
        self.contentView.addSubview(timeLabel)
        timeLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(buyLabel)
            make.right.equalToSuperview().offset(-16)
        }
        
        self.contentView.addSubview(positionBtn)
        positionBtn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(76)
            make.height.equalTo(30)
            make.width.equalTo(80)
        }
        
        self.contentView.addSubview(stateBtn)
        stateBtn.isHidden = true
        stateBtn.nameLabel.textColor = kThemeColor
        stateBtn.photoImageView.image = UIImage(named: "entrustArrow")
        stateBtn.snp.makeConstraints { (make) in
            make.right.right.equalToSuperview().offset(-15)
            make.centerY.equalTo(buyLabel)
            make.width.equalTo(40)
            make.height.equalTo(40)
        }
        stateBtn.photoImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview()
            make.centerY.equalToSuperview()
        }
        stateBtn.nameLabel.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-12)
            make.centerY.equalToSuperview()
        }
        
        self.contentView.addSubview(scalePriceLabel)
        scalePriceLabel.snp.makeConstraints { (make) in
            make.centerY.equalTo(buyLabel)
            make.right.equalToSuperview().offset(-15)
        }
        
        for i in 0..<6 {
            let titleLabel = BaseLabel(style: .thirdStyle)
            titleLabel.font = UIFont.systemFont(ofSize: 12)
            titleLabel.tag = nameTag + i
            titleLabel.isHidden = true
            self.contentView.addSubview(titleLabel)
            titleLabel.snp.makeConstraints { (make) in
                make.top.equalToSuperview().offset(i<3 ? 50:100)
                make.left.equalToSuperview().offset(15+CGFloat(Int(i%3))*(kSCREEN_WIDTH)/3)
                make.width.equalTo((kSCREEN_WIDTH)/3)
                make.height.equalTo(12)
            }
            
            let numberLabel = BaseLabel(style: .oneStyle)
            numberLabel.font = UIFont.systemFont(ofSize: 14)
            numberLabel.isHidden = true
            numberLabel.tag = inforTag + i
            self.contentView.addSubview(numberLabel)
            numberLabel.snp.makeConstraints { (make) in
                make.centerX.equalTo(titleLabel)
                make.width.equalTo((kSCREEN_WIDTH-30)/3)
                make.top.equalTo(titleLabel.snp.bottom).offset(10)
                make.height.equalTo(14)
            }
            
            if i == 0 {
                entrustLabel = numberLabel
            }else if i == 1 {
                zsLabel = numberLabel
            }else if i == 2 {
                syLabel = numberLabel
            }else if i == 3 {
                dqLabel = numberLabel
            }else if i == 4 {
                zyLabel = numberLabel
            }
        }
    }
    
    func exchangeOderType(model:CoinOrderModel, type:OrderSelectType) {
        self.model = model
        self.type = type
        buyLabel.text = String(format: "%@%@", model.tradeType == 0 ? "市价":"限价",model.position == 0 ? "买入" : "卖出" )
        buyLabel.textColor = model.position != 0 ? kRedColor : kGreenColor
        eventLabel.text = String(format: "%@/%@", model.targetCoin,model.sourceCoin)
        let stopLossStr = "止损"
        let stopPrifitStr = "止盈"
//        ///委托价 买入价
        let tradePrice  = CYCalculate.cy_intercept(number: model.tradePrice, digit: 6)
        ///委托量
        let tradeNumber = CYCalculate.cy_intercept(number: model.tradeAmount, digit: 6)

        //止损止盈
        zsLabel?.text = "-" + CYCalculate.cy_intercept(number: model.stopLoss, digit: 6)! + "%"
        zyLabel?.text = "+" + CYCalculate.cy_intercept(number: model.stopProfit, digit: 6)! + "%"
        
        if type == .orderEntrust {
            if model.createTime != 0 {
                let timeStr = Helper.timeWithTimeIntervalString(timeStr: Int(model.createTime))
                timeLabel.text = timeStr
            }else {
                timeLabel.text = ""
            }
            
            var titleName = ""
            var coinName = ""
            var amountName = model.targetCoin
            if model.tradeType == 0 {
                if model.position == 0 {
                    titleName = "委托额"
                    coinName = model.sourceCoin
                    amountName  = model.sourceCoin
                }else {
                    titleName = "委托量"
                    coinName = model.targetCoin
                }
                entrustLabel?.text = tradeNumber
            }else {
              titleName = "委托价"
             coinName = model.sourceCoin
              entrustLabel?.text = tradePrice
            }
            let priceStr = String(format: "%@(%@)",titleName,  coinName)
            let currentStr = String(format: "当前价(%@)", model.sourceCoin)
            scheduleLabel.text = String(format: "%@/%@ %@", CYCalculate.cy_intercept(number: model.dealAmount, digit: 6)!,CYCalculate.cy_intercept(number: model.tradeAmount, digit: 6)!,amountName)
            dqLabel?.text = CYCalculate.cy_intercept(number: model.dealPrice, digit: 6)
            let arr = [priceStr,stopLossStr,currentStr,stopPrifitStr]
            self.changeStates(type: type, titleArr: arr)
            positionBtn.setTitle("撤单", for: UIControlState.normal)
    
        }else if type == .orderPosition {
            let priceStr = String(format: "买入价(%@)", model.sourceCoin)
            let currentStr = String(format: "最新价(%@)", model.sourceCoin)
            dqLabel?.text = CYCalculate.cy_intercept(number: model.nyxPrice, digit: 6)
            let arr = [priceStr,stopLossStr,currentStr,stopPrifitStr]
            self.changeStates(type: type, titleArr: arr)
            positionBtn.setTitle("平仓", for: UIControlState.normal)
            
            scheduleLabel.text = String(format: "%@", CYCalculate.cy_intercept(number: model.holdPosition, digit: 6)!)
            self.changeStates(type: type, titleArr: arr)
        }else {
            let priceStr = String(format: "买入价(%@)", model.sourceCoin)
            let currentStr = String(format: "平仓价(%@)", model.sourceCoin)
            let profitStr = String(format: "平仓收益(%@)", model.sourceCoin)
            let arr = [priceStr,currentStr,profitStr]
            

            self.changeStates(type: type, titleArr: arr)
            
            stateBtn.photoImageView.isHidden = false
            stateBtn.nameLabel.textColor = kThemeColor
            stateBtn.nameLabel.snp.updateConstraints { (make) in
                make.right.equalToSuperview().offset(-12)
                make.centerY.equalToSuperview()
            }
            if model.status == 0 || model.status == 1 || model.status == 3 || model.status == 5{
                stateBtn.nameLabel.text = kText("撤销")
                stateBtn.photoImageView.isHidden = true
                stateBtn.nameLabel.snp.updateConstraints { (make) in
                    make.right.equalToSuperview().offset(0)
                }
            }else if model.status == 2 {
                stateBtn.nameLabel.text = kText("完全成交")
            }else if model.status == 4 {
                stateBtn.nameLabel.text = kText("部分成交已撤")
            }else if model.status == 6 {
                stateBtn.nameLabel.text = kText("已撤销")
                stateBtn.photoImageView.isHidden = true
                stateBtn.nameLabel.textColor = KUseTitleColor
                stateBtn.nameLabel.snp.updateConstraints { (make) in
                    make.right.equalToSuperview().offset(0)
                    make.centerY.equalToSuperview()
                }
            }
            
        }
        
    }
    
    func changeStates(type:OrderSelectType,titleArr:[String]) {
        stateBtn.isHidden = true
        positionBtn.isHidden = false
        timeLabel.isHidden = false
        
        
        if type == .orderHistory {
            stateBtn.isHidden = false
            positionBtn.isHidden = true
            timeLabel.isHidden = true
            for i in 0 ..< titleArr.count {
                let label = self.contentView.viewWithTag(i+nameTag) as? UILabel
                label?.text = titleArr[i]
                label?.isHidden = false
            }
            entrustLabel?.isHidden = false
            zsLabel?.isHidden = false
            syLabel?.isHidden = false
            
        }else {
            for i in 0 ..< titleArr.count {
                var label:UILabel?
                if i >= 2 {
                    label = self.contentView.viewWithTag(i+nameTag+1) as? UILabel
                }else {
                    label = self.contentView.viewWithTag(i+nameTag) as? UILabel
                }
                label?.text = titleArr[i]
                label?.isHidden = false
            }
            entrustLabel?.isHidden = false
            zsLabel?.isHidden = false
            zyLabel?.isHidden = false
            dqLabel?.isHidden = false
        }
    }
    
    
    /// 撤单/平仓
    @objc func positionBtnAction() {
        if type == .orderPosition {
            if delegate != nil && delegate?.changePositionState != nil{
                self.delegate?.changePositionState(self.model)
            }
        }else {
        if delegate != nil && delegate?.changeStates != nil {
            self.delegate?.changeStates(self.model)
        }
        }
    }
    

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

}
